package com.levi.test.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

import static com.levi.test.constant.ExecuteCommonData.CHARSET;

public class SecretUtil {

    private static final String STR = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM`-=~!@#$%^&*()_+[];',./{}|:<>? \\\"";

    private static final String[] list = STR.split("");

    private static final String KEY = "8e07dafd13495561db9063ebe4db4b27";

    public static String secret(String msg, boolean flag) {
        if (msg == null || msg.equals("")) {
            return msg;
        }
        try {
            if (flag) {
                String hexStr = URLEncoder.encode(msg, CHARSET);
                String sec = secretInner(hexStr, true);
                return sec;
            } else {
                String sec = secretInner(msg, false);
                String res = URLDecoder.decode(sec, CHARSET);
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String secretInner(String msg, boolean flag) {
        if (msg == null || msg.equals("")) {
            return msg;
        }
        String[] sArr = KEY.split("");
        String[] mArr = msg.split("");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mArr.length; i++) {
            String m = mArr[i];
            int mi = STR.indexOf(m);
            if (mi < 0) {
                sb.append(m);
                continue;
            }
            int si = STR.indexOf(sArr[i % KEY.length()]);
            if (flag) {
                sb.append(list[(mi + si) % list.length]);
            } else {
                int c = mi - si;
                sb.append(list[c >= 0 ? c : list.length + c]);
            }
        }
        return sb.toString();
    }
}
